package me.flyray.bsin.gateway.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import me.flyray.bsin.context.LoginInfoContextHelper;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.gateway.common.CommonConstants;

/**
 * @author ：bolei
 * @date ：Created in 2021/12/17 13:02
 * @description：
 * @modified By：
 */
public class IpfsTokenValidationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException, BusinessException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 防止流读取一次后就没有了, 所以需要将流继续写出去
        //获取用户凭证
        // 校验token
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            System.out.println(s + ":" + httpServletRequest.getHeader(s));
        }
        System.out.println(httpServletRequest.getHeaderNames());
        // TODO filter中获取不到el-upload的请求头
        String token = httpServletRequest.getHeader("Authorization");
        String content = httpServletRequest.getHeader("Content-Type");

//        if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
//            parseToken(httpServletRequest, null, request, response);
//            chain.doFilter(request, response);
//            return;
//        }

        if (StringUtils.isNotBlank(token)) {
            // 将异常分发到/error/exthrow控制器
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            request.getRequestDispatcher("/exthrow").forward(request, httpServletResponse);
            return;
        }

        // 解析token    校验token
        JWT jwt = null;
        try {
            jwt = JWTUtil.parseToken(token);
            boolean verify = jwt.setKey(CommonConstants.JWT_SECRET.getBytes()).verify();
//                boolean validate = jwt.validate(0);
//                if(!verify || !validate){
//                    // 将异常分发到/error/exthrow控制器
//                    request.getRequestDispatcher("/error/exthrow").forward(request,response);
//                    return;
//                }
        } catch (Exception e) {
            System.out.println(e);
            // 将异常分发到/error/exthrow控制器
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            request.getRequestDispatcher("/exthrow").forward(request, httpServletResponse);
            return;
        }
        //将jwt里存储的数据全部注入到 LoginInfoContextHelper里
        cn.hutool.json.JSONObject payloadJson = jwt.getPayloads();
        JSONObject loginJson = JSON.parseObject(payloadJson.toString());
        loginJson.put("token",token);
        LoginInfoContextHelper.setLoginUser(loginJson);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    public String createToken(Map<String, Object> payload) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 1);
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        String token = JWTUtil.createToken(payload, "1234".getBytes());
        return token;
    }


    public static void main(String[] args) {

        Map<String, Object> map = new HashMap<String, Object>();
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 1);
        //签发时间
        map.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        map.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        map.put(JWTPayload.NOT_BEFORE, now);
        String token = JWTUtil.createToken(map, "1234".getBytes());
        System.out.println(token);
        JWT jwt = JWTUtil.parseToken(token);
        System.out.println(jwt);


    }
}
